package notes.java.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 模拟200个请求，并发10个，同一时间内能获取到许可就执行，否则就丢弃处理
 * @author wangcs
 *
 */
public class U10_TestSemaphore {

	// 线程数200个
	private static int threadNum = 200;
	public static void main(String[] args) {
		// 线程池
		ExecutorService service = Executors.newCachedThreadPool();
		// 并发量为10
		Semaphore semaphore = new Semaphore(10);
		for(int i=0; i<threadNum; i++) {
			int count = i; 
			service.execute(()->{
				if(semaphore.tryAcquire()) { // 尝试获取许可，获取不到就丢弃处理
					test(count);
					semaphore.release(); // 释放许可
				}
			});
		}
	}
	
	private static void test(int i) {
		System.out.println("run..." + i);
	}
}
